from ListView import WebListView, WebListViewDelegateBuilder
from BaseControl import WebFindKey
from Exeptions import ElementNotFoundException, WebControlException
from selenium.common.exceptions import MoveTargetOutOfBoundsException


class WebComboBox(WebListView):
    def __init__(self, handler, delegateBuilder=WebListViewDelegateBuilder()):
        super(WebComboBox, self).__init__(handler, delegateBuilder)

    def rootDelegate(self):
        containerState = self.get_attribute('class')
        if "closed" in containerState:
            self.waitChildControl(WebFindKey.TAG_NAME, 'span').click()
        return self._delegateBuilder.build(self.getChildControl(WebFindKey.TAG_NAME, 'div'))

    def selectItems(self, predicate):
        try:
            self.itemsFor(predicate)[0].setSelection(True)
        except IndexError:
            raise ElementNotFoundException("combobox")
        # except MoveTargetOutOfBoundsException as e:
        #     raise WebControlException("Combobox: %s" % e.message)

    def currentItem(self):
        return self.selectedItems()[0]

    # def selectItems(self, predicate):
    #     self.transformItems(lambda x: predicate(x), lambda x: x.click())

